package com.agileboot.admin.controller.airport;

import com.agileboot.admin.customize.aop.accessLog.AccessLog;
import com.agileboot.common.core.base.BaseController;
import com.agileboot.common.core.dto.ResponseDTO;
import com.agileboot.common.core.page.PageDTO;
import com.agileboot.common.enums.common.BusinessTypeEnum;
import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.agileboot.common.utils.poi.CustomExcelUtil;
import com.agileboot.domain.airport.selfcheck.command.AddSirSelfCheckCommand;
import com.agileboot.domain.airport.selfcheck.db.SirSelfCheckEntity;
import com.agileboot.domain.airport.selfcheck.db.SirSelfCheckMapper;
import com.agileboot.domain.airport.selfcheck.query.SirSelfCheckQuery;
import com.agileboot.domain.airport.selfcheck.db.SirSelfCheckServiceImpl;
import com.agileboot.domain.airport.selfcheck.dto.SirSelfCheckDTO;

import java.util.*;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * 安全检查 API
 *
 * @author [your-name]
 */
@Tag(name = "安全检查", description = "安全检查相关的增删查改")
@RestController
@RequestMapping("/airport/SirSelfCheck")
@Validated
@RequiredArgsConstructor
public class SirSelfCheckController extends BaseController {

    private final SirSelfCheckServiceImpl service;
    private final SirSelfCheckMapper mapper;

    /**
     * 获取安全检查列表
     */
    @Operation(summary = "安全检查列表")
    @GetMapping("/list")
    public ResponseDTO<PageDTO<SirSelfCheckDTO>> list(SirSelfCheckQuery query) {
        PageDTO<SirSelfCheckDTO> pageDTO = service.getPageList(query);
        return ResponseDTO.ok(pageDTO);
    }

    /**
     * 专业查询条件
     * @return
     */
    @GetMapping("/getProfessional")
    public ResponseDTO<List<String>> getProfessional() {
        return ResponseDTO.ok(mapper.getProfessional());
    }

    /**
     * 导出安全检查列表
     */
    @Operation(summary = "导出安全检查")
    @AccessLog(title = "安全检查管理", businessType = BusinessTypeEnum.EXPORT)
    @GetMapping("/excel")
    public void export(HttpServletResponse response, SirSelfCheckQuery query) {
        List<SirSelfCheckDTO> all = service.getList(query);
        CustomExcelUtil.writeToResponse(all, SirSelfCheckDTO.class, response);
    }

    /**
     * 获取安全检查详情
     */
    @Operation(summary = "安全检查详情")
    @GetMapping("/{id}")
    public ResponseDTO<SirSelfCheckDTO> getInfo(@PathVariable Long id) {
        return ResponseDTO.ok(service.getInfo(id));
    }

    /**
     * 保存安全检查
     */
    @Operation(summary = "新增安全检查")
    @AccessLog(title = "安全检查管理", businessType = BusinessTypeEnum.ADD)
    @PostMapping("/save")
    public ResponseDTO<Void> add(@RequestBody AddSirSelfCheckCommand bo) {
        service.saveOrUpdateSirSelfCheck(bo);
        return ResponseDTO.ok();
    }

    /**
     * 删除安全检查
     */
    @Operation(summary = "删除安全检查")
    @AccessLog(title = "安全检查管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping
    public ResponseDTO<Void> remove(@RequestParam @NotNull @NotEmpty List<Long> ids) {
        service.deleteSirSelfCheck(ids);
        return ResponseDTO.ok();
    }

    /**
     * 批量设置归属部门
     */
    @Operation(summary = "批量设置归属部门")
    @PostMapping("/batchSetDept")
    public ResponseDTO<Void> batchSetDept(@RequestBody AddSirSelfCheckCommand bo) {
        service.batchUpdateBelongDept(bo.getIds(), bo.getBelongDept());
        return ResponseDTO.ok();
    }

    /**
     * 批量设置标签
     */
    @Operation(summary = "批量设置标签")
    @PostMapping("/batchSetTag")
    public ResponseDTO<Void> batchSetTag(@RequestBody AddSirSelfCheckCommand bo) {
        service.batchUpdateTagId(bo.getIds(), bo.getTagId());
        return ResponseDTO.ok();
    }

    /**
     * 下载模板
     */
    @Operation(summary = "Download Template")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 创建模板数据列表
            List<SirSelfCheckDTO> templateData = new ArrayList<>();

            // 使用 Apache POI 创建工作簿和工作表
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("Template");

            // 创建表头行（不包含主键ID）
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"序号", "专业", "检查内容", "检查标准编号", "检查标准", "符合性判定标准", "检查方式", "公司依据", "公司条款", "法律法规依据", "法律法规条款", "基础周期", "融合来源", "检查涉及部门"};
            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 设置响应头进行文件下载
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=\"部门数据模板.xlsx\"");

            // 写入响应输出流
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            // 处理异常
            throw new ApiException(e, ErrorCode.Internal.EXCEL_PROCESS_ERROR, "Error generating the template");
        }
    }

    /**
     * 上传并导入数据
     */
    @Operation(summary = "Upload and Import Data")
    @PostMapping("/importData")
    public ResponseDTO<Map<String, Integer>> importData(@RequestParam("file") MultipartFile file,
                                                        @RequestParam("belongDept") Long belongDept) {
        try {
            // 解析 Excel 文件
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = workbook.getSheetAt(0);
            DataFormatter dataFormatter = new DataFormatter();

            List<SirSelfCheckEntity> entitiesToInsert = new ArrayList<>();

            int addedCount = 0;

            // 遍历 Excel 工作表中的行
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                XSSFRow row = sheet.getRow(i);
                if (row == null) continue;

                SirSelfCheckDTO data = new SirSelfCheckDTO();

                // 将每一列映射到 SirSelfCheckDTO 字段（不包括 ID）
                if (row.getCell(0) != null) {
                    data.setSeq((int) row.getCell(0).getNumericCellValue()); // 序号
                }
                if (row.getCell(1) != null) {
                    data.setProfessional(dataFormatter.formatCellValue(row.getCell(1)));
                }
                if (row.getCell(2) != null) {
                    data.setCheckContent(dataFormatter.formatCellValue(row.getCell(2)));
                }
                if (row.getCell(3) != null) {
                    data.setCheckStandardCode(dataFormatter.formatCellValue(row.getCell(3)));
                }
                if (row.getCell(4) != null) {
                    data.setCheckStandard(dataFormatter.formatCellValue(row.getCell(4)));
                }
                if (row.getCell(5) != null) {
                    data.setComplianceCriteria(dataFormatter.formatCellValue(row.getCell(5)));
                }
                if (row.getCell(6) != null) {
                    data.setCheckMethod(dataFormatter.formatCellValue(row.getCell(6)));
                }
                if (row.getCell(7) != null) {
                    data.setCompanyBasis(dataFormatter.formatCellValue(row.getCell(7)));
                }
                if (row.getCell(8) != null) {
                    data.setCompanyClause(dataFormatter.formatCellValue(row.getCell(8)));
                }
                if (row.getCell(9) != null) {
                    data.setLawsBasis(dataFormatter.formatCellValue(row.getCell(9)));
                }
                if (row.getCell(10) != null) {
                    data.setLawsClause(dataFormatter.formatCellValue(row.getCell(10)));
                }
                if (row.getCell(11) != null) {
                    data.setBaseCycle(dataFormatter.formatCellValue(row.getCell(11)));
                }
                if (row.getCell(12) != null) {
                    data.setIntegrationSource(dataFormatter.formatCellValue(row.getCell(12)));
                }
                if (row.getCell(13) != null) {
                    data.setCheckDepartments(dataFormatter.formatCellValue(row.getCell(13)));
                }

                // 将每条数据设置好对应的 `belongDept` 和 `updateTime`
                SirSelfCheckEntity newEntity = new SirSelfCheckEntity();
                BeanUtils.copyProperties(data, newEntity);
                newEntity.setCreateTime(new Date());
                newEntity.setUpdateTime(new Date());
                newEntity.setBelongDept(belongDept); // 设置部门

                // 将新实体添加到批量插入列表中
                entitiesToInsert.add(newEntity);
                addedCount++;
            }

            // 批量插入所有数据
            if (!entitiesToInsert.isEmpty()) {
                service.saveBatch(entitiesToInsert);
            }

            // 返回操作结果
            Map<String, Integer> result = new HashMap<>();
            result.put("added", addedCount);
            return ResponseDTO.ok(result);
        } catch (Exception e) {
            return ResponseDTO.fail(new ApiException(ErrorCode.Business.UPLOAD_FILE_FAILED));
        }
    }
}
